<template>
  <div class="audio-tools">
    <ToolContainer
      tool-name="音频处理"
      default-tab="convert"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- 格式转换标签页 -->
        <el-tab-pane label="格式转换" name="convert">
          <ToolSection
            show-upload
            upload-text="拖拽音频文件到此处或点击上传"
            upload-tip="支持MP3、WAV、OGG、AAC等格式"
            :upload-icon="UploadFilled"
            accept="audio/*"
            :multiple="true"
            :show-file-list="true"
            @file-change="handleFileChange"
          >
            <template #preview>
              <div v-if="audioFiles.length" class="audio-preview">
                <div v-for="file in audioFiles" :key="file.uid" class="audio-item">
                  <div class="audio-info">
                    <p><strong>文件名：</strong>{{ file.name }}</p>
                    <p><strong>大小：</strong>{{ file.sizeText }}</p>
                    <p><strong>时长：</strong>{{ file.duration || '未知' }}</p>
                  </div>
                  <audio v-if="file.url" :src="file.url" controls class="audio-player"></audio>
                </div>
              </div>
            </template>

            <template #options>
              <div v-if="audioFiles.length" class="convert-options">
                <el-form label-width="100px">
                  <el-form-item label="目标格式">
                    <el-select v-model="targetFormat" placeholder="选择目标格式">
                      <el-option label="MP3" value="mp3" />
                      <el-option label="WAV" value="wav" />
                      <el-option label="OGG" value="ogg" />
                      <el-option label="AAC" value="aac" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="音质设置">
                    <el-select v-model="quality" placeholder="选择音质">
                      <el-option label="高质量 (320kbps)" value="320" />
                      <el-option label="标准质量 (192kbps)" value="192" />
                      <el-option label="普通质量 (128kbps)" value="128" />
                      <el-option label="低质量 (96kbps)" value="96" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleConvert" 
                :loading="loading"
                :disabled="audioFiles.length === 0"
              >
                批量转换
              </el-button>
              <el-button 
                type="success" 
                @click="handleBatchDownload" 
                :loading="loading"
                :disabled="convertedFiles.length === 0"
              >
                批量下载
              </el-button>
            </template>

            <template #result>
              <div v-if="convertedFiles.length" class="convert-results">
                <h4>转换结果：</h4>
                <div class="result-list">
                  <div v-for="file in convertedFiles" :key="file.name" class="result-item">
                    <span class="file-name">{{ file.name }}</span>
                    <el-button size="small" @click="downloadFile(file)">下载</el-button>
                  </div>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 音频剪辑标签页 -->
        <el-tab-pane label="音频剪辑" name="edit">
          <ToolSection
            show-upload
            upload-text="拖拽音频文件到此处或点击上传"
            upload-tip="支持MP3、WAV等格式"
            :upload-icon="UploadFilled"
            accept="audio/*"
            @file-change="handleSingleFileChange"
          >
            <template #preview>
              <div v-if="currentAudio" class="audio-editor">
                <div class="audio-info">
                  <p><strong>文件名：</strong>{{ currentAudio.name }}</p>
                  <p><strong>时长：</strong>{{ currentAudio.duration || '未知' }}</p>
                </div>
                <audio v-if="currentAudio.url" :src="currentAudio.url" controls class="audio-player"></audio>
              </div>
            </template>

            <template #options>
              <div v-if="currentAudio" class="edit-options">
                <el-form label-width="100px">
                  <el-form-item label="开始时间">
                    <el-input-number 
                      v-model="startTime" 
                      :min="0" 
                      :max="endTime - 1"
                      :step="0.1"
                      placeholder="秒"
                    />
                  </el-form-item>
                  <el-form-item label="结束时间">
                    <el-input-number 
                      v-model="endTime" 
                      :min="startTime + 1" 
                      :step="0.1"
                      placeholder="秒"
                    />
                  </el-form-item>
                  <el-form-item label="淡入效果">
                    <el-switch v-model="fadeIn" />
                  </el-form-item>
                  <el-form-item label="淡出效果">
                    <el-switch v-model="fadeOut" />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleTrim" 
                :loading="loading"
                :disabled="!currentAudio"
              >
                剪辑音频
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownloadTrimmed" 
                :loading="loading"
                :disabled="!trimmedAudio"
              >
                下载剪辑
              </el-button>
            </template>

            <template #result>
              <div v-if="trimmedAudio" class="trim-result">
                <h4>剪辑结果：</h4>
                <audio :src="trimmedAudio.url" controls class="audio-player"></audio>
                <p>剪辑时长：{{ (endTime - startTime).toFixed(1) }}秒</p>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 音量调节标签页 -->
        <el-tab-pane label="音量调节" name="volume">
          <ToolSection
            show-upload
            upload-text="拖拽音频文件到此处或点击上传"
            upload-tip="支持MP3、WAV等格式"
            :upload-icon="UploadFilled"
            accept="audio/*"
            @file-change="handleSingleFileChange"
          >
            <template #preview>
              <div v-if="currentAudio" class="audio-volume">
                <div class="audio-info">
                  <p><strong>文件名：</strong>{{ currentAudio.name }}</p>
                </div>
                <audio v-if="currentAudio.url" :src="currentAudio.url" controls class="audio-player"></audio>
              </div>
            </template>

            <template #options>
              <div v-if="currentAudio" class="volume-options">
                <el-form label-width="100px">
                  <el-form-item label="音量调节">
                    <el-slider
                      v-model="volumeLevel"
                      :min="-20"
                      :max="20"
                      :step="1"
                      show-input
                      :format-tooltip="formatVolume"
                    />
                  </el-form-item>
                  <el-form-item label="预设选项">
                    <el-radio-group v-model="volumePreset">
                      <el-radio label="quiet">安静 (-10dB)</el-radio>
                      <el-radio label="normal">正常 (0dB)</el-radio>
                      <el-radio label="loud">响亮 (+10dB)</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleVolumeAdjust" 
                :loading="loading"
                :disabled="!currentAudio"
              >
                调节音量
              </el-button>
              <el-button 
                type="success" 
                @click="handleDownloadAdjusted" 
                :loading="loading"
                :disabled="!adjustedAudio"
              >
                下载调节后音频
              </el-button>
              <el-button 
                @click="applyPreset"
                :disabled="!volumePreset"
              >
                应用预设
              </el-button>
            </template>

            <template #result>
              <div v-if="adjustedAudio" class="volume-result">
                <h4>音量调节结果：</h4>
                <audio :src="adjustedAudio.url" controls class="audio-player"></audio>
                <p>音量调节：{{ volumeLevel > 0 ? '+' : '' }}{{ volumeLevel }}dB</p>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

interface AudioFile {
  uid: string
  name: string
  size: number
  sizeText: string
  raw: File
  url?: string
  duration?: string
}

interface ProcessedAudio {
  name: string
  url: string
  blob: Blob
}

// 基础数据
const loading = ref(false)
const showIntro = ref(true)
const featureConfig = featuresConfig.audioTools

// 音频文件相关
const audioFiles = ref<AudioFile[]>([])
const currentAudio = ref<AudioFile | null>(null)

// 格式转换相关
const targetFormat = ref('mp3')
const quality = ref('192')
const convertedFiles = ref<ProcessedAudio[]>([])

// 音频剪辑相关
const startTime = ref(0)
const endTime = ref(30)
const fadeIn = ref(false)
const fadeOut = ref(false)
const trimmedAudio = ref<ProcessedAudio | null>(null)

// 音量调节相关
const volumeLevel = ref(0)
const volumePreset = ref('normal')
const adjustedAudio = ref<ProcessedAudio | null>(null)

// 监听预设变化
watch(volumePreset, (newPreset) => {
  switch (newPreset) {
    case 'quiet':
      volumeLevel.value = -10
      break
    case 'normal':
      volumeLevel.value = 0
      break
    case 'loud':
      volumeLevel.value = 10
      break
  }
})

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

function formatVolume(val: number): string {
  return `${val > 0 ? '+' : ''}${val}dB`
}

function handleTabChange(tabName: string) {
  console.log('切换到标签页:', tabName)
}

function handleFileChange(file: any, fileList: any[]) {
  audioFiles.value = []
  fileList.forEach(async (item) => {
    const audioFile: AudioFile = {
      uid: item.uid,
      name: item.name,
      size: item.size,
      sizeText: formatFileSize(item.size),
      raw: item.raw
    }
    
    // 创建音频URL用于预览
    audioFile.url = URL.createObjectURL(item.raw)
    
    // 获取音频时长
    try {
      const duration = await getAudioDuration(audioFile.url)
      audioFile.duration = formatDuration(duration)
    } catch (error) {
      console.error('获取音频时长失败:', error)
    }
    
    audioFiles.value.push(audioFile)
  })
}

function handleSingleFileChange(file: any) {
  if (!file) return
  
  const audioFile: AudioFile = {
    uid: file.uid,
    name: file.name,
    size: file.size,
    sizeText: formatFileSize(file.raw.size),
    raw: file.raw
  }
  
  // 创建音频URL用于预览
  audioFile.url = URL.createObjectURL(file.raw)
  
  // 获取音频时长
  getAudioDuration(audioFile.url).then(duration => {
    audioFile.duration = formatDuration(duration)
    endTime.value = Math.min(duration, 30) // 默认剪辑30秒或文件长度
  }).catch(error => {
    console.error('获取音频时长失败:', error)
  })
  
  currentAudio.value = audioFile
}

function getAudioDuration(url: string): Promise<number> {
  return new Promise((resolve, reject) => {
    const audio = new Audio()
    audio.addEventListener('loadedmetadata', () => {
      resolve(audio.duration)
    })
    audio.addEventListener('error', reject)
    audio.src = url
  })
}

function formatDuration(seconds: number): string {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

async function handleConvert() {
  if (audioFiles.value.length === 0) {
    ElMessage.warning('请先上传音频文件')
    return
  }
  
  loading.value = true
  convertedFiles.value = []
  
  try {
    for (const file of audioFiles.value) {
      // 模拟音频转换过程
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 创建转换后的文件（这里只是模拟，实际需要使用音频处理库）
      const convertedBlob = new Blob([file.raw], { type: `audio/${targetFormat.value}` })
      const convertedUrl = URL.createObjectURL(convertedBlob)
      
      convertedFiles.value.push({
        name: file.name.replace(/\.[^.]+$/, `.${targetFormat.value}`),
        url: convertedUrl,
        blob: convertedBlob
      })
    }
    
    ElMessage.success('音频转换完成')
  } catch (error) {
    ElMessage.error('转换失败：' + error.message)
  } finally {
    loading.value = false
  }
}

async function handleTrim() {
  if (!currentAudio.value) {
    ElMessage.warning('请先上传音频文件')
    return
  }
  
  if (startTime.value >= endTime.value) {
    ElMessage.warning('开始时间必须小于结束时间')
    return
  }
  
  loading.value = true
  
  try {
    // 模拟音频剪辑过程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 创建剪辑后的文件（这里只是模拟）
    const trimmedBlob = new Blob([currentAudio.value.raw], { type: 'audio/mp3' })
    const trimmedUrl = URL.createObjectURL(trimmedBlob)
    
    trimmedAudio.value = {
      name: currentAudio.value.name.replace(/\.[^.]+$/, '_trimmed.mp3'),
      url: trimmedUrl,
      blob: trimmedBlob
    }
    
    ElMessage.success('音频剪辑完成')
  } catch (error) {
    ElMessage.error('剪辑失败：' + error.message)
  } finally {
    loading.value = false
  }
}

async function handleVolumeAdjust() {
  if (!currentAudio.value) {
    ElMessage.warning('请先上传音频文件')
    return
  }
  
  loading.value = true
  
  try {
    // 模拟音量调节过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建音量调节后的文件（这里只是模拟）
    const adjustedBlob = new Blob([currentAudio.value.raw], { type: 'audio/mp3' })
    const adjustedUrl = URL.createObjectURL(adjustedBlob)
    
    adjustedAudio.value = {
      name: currentAudio.value.name.replace(/\.[^.]+$/, '_volume_adjusted.mp3'),
      url: adjustedUrl,
      blob: adjustedBlob
    }
    
    ElMessage.success('音量调节完成')
  } catch (error) {
    ElMessage.error('音量调节失败：' + error.message)
  } finally {
    loading.value = false
  }
}

function handleBatchDownload() {
  if (convertedFiles.value.length === 0) {
    ElMessage.warning('没有可下载的文件')
    return
  }
  
  convertedFiles.value.forEach(file => {
    downloadFile(file)
  })
  
  ElMessage.success('批量下载开始')
}

function handleDownloadTrimmed() {
  if (!trimmedAudio.value) {
    ElMessage.warning('请先剪辑音频')
    return
  }
  
  downloadFile(trimmedAudio.value)
}

function handleDownloadAdjusted() {
  if (!adjustedAudio.value) {
    ElMessage.warning('请先调节音量')
    return
  }
  
  downloadFile(adjustedAudio.value)
}

function downloadFile(file: ProcessedAudio) {
  const a = document.createElement('a')
  a.href = file.url
  a.download = file.name
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  
  ElMessage.success(`${file.name} 下载成功`)
}

function applyPreset() {
  if (!volumePreset.value) {
    ElMessage.warning('请选择预设选项')
    return
  }
  
  ElMessage.success(`已应用${volumePreset.value}预设`)
}
</script>

<style scoped>
.audio-tools {
  position: relative;
}

.audio-preview {
  width: 100%;
}

.audio-item,
.audio-editor,
.audio-volume {
  margin-bottom: 20px;
  padding: 16px;
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
}

.audio-info {
  margin-bottom: 12px;
}

.audio-info p {
  margin: 8px 0;
  color: var(--el-text-color-primary, #303133);
}

.audio-player {
  width: 100%;
  margin-top: 12px;
}

.convert-options,
.edit-options,
.volume-options {
  width: 100%;
}

.convert-results,
.trim-result,
.volume-result {
  width: 100%;
  padding: 16px;
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
}

.convert-results h4,
.trim-result h4,
.volume-result h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light, #e4e7ed);
}

.file-name {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  color: var(--el-text-color-primary, #303133);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .audio-item,
  .audio-editor,
  .audio-volume {
    padding: 12px;
  }
  
  .result-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style> 